import {get, update, post} from './request';
import Storage from '@/utils/storage';
import {DeviceEventEmitter} from 'react-native';

export async function getUserInfo(dispatch) {
  const res = await get('/system/user');
  const userInfo = res?.data?.data ?? {};
  dispatch?.({
    type: 'CHANGE_USERINFO',
    userInfo,
  });
  return userInfo;
}

export async function updateUserInfo(params, dispatch) {
  const res = await update('/system/user', params);
  let userInfo = {};
  if (res?.code === 0) {
    userInfo = await getUserInfo(dispatch);
  }
  return userInfo ?? {};
}

export async function logout(navigation, noshow) {
  let res = await post('/system/logout');
  await Storage.remove('token');
  if (res.code === 0) {
    navigation.navigate('Login');
    !noshow &&
      DeviceEventEmitter.emit('toast', {
        message: '操作成功,请重新重新登录！！',
        type: 'success',
      });
  }
  return res;
}

export async function changepwd(params, navigation) {
  const res = await update('/system/user', params);
  let userInfo = {};
  if (res?.code === 0) {
    userInfo = await logout(navigation);
  }
  return userInfo ?? {};
}

export async function join(params, dispatch) {
  const res = await update('/system/user', params);
  if (res?.code === 0) {
    await getUserInfo(dispatch);
  }
  return res ?? {};
}
